<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    width="800px"
    :visible.sync="visible"
    @cancel="close"
  >
    <el-form ref="form" v-loading="loading" label-width="100px" :rules="rules" size="medium" :model="form">
      <el-form-item prop="icon" label="图标">
        <div style="display: flex;align-items: flex-end">
          <el-upload
            class="fl app-uploader-img-plus"
            :action="actionUrl"
            :show-file-list="false"
            :headers="uploadHeaders"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="icon" :src="icon" class="avatar">
            <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
          </el-upload>

          <div style="line-height: normal;margin-left: 20px">
            <div>图片要求：</div>
            <div>1.上传的图片限制文件大小限制1MB，仅支持JPG、PNG格式</div>
            <div>2.建议尺寸： 100*100像素</div>
          </div>
        </div>

      </el-form-item>

      <el-form-item prop="name" label="功能名称">
        <el-input v-model="form.name" placeholder="请填入内容" />
      </el-form-item>
      <el-form-item prop="code" label="功能编码">
        <el-input v-model="form.code" placeholder="请填入内容" />
      </el-form-item>

      <el-form-item prop="description" label="描述">
        <el-input v-model="form.description" type="textarea" placeholder="请填入内容" />
      </el-form-item>

      <el-form-item prop="permGroups" label="权限集">
        <el-select v-model="form.permGroups" multiple style="width: 620px" placeholder="请选择">
          <el-option
            v-for="item in groupList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="webUrl" label="设置路径">
        <el-input v-model="form.webUrl" placeholder="请填入内容" />
      </el-form-item>

      <el-form-item style="line-height: 1.2" prop="helperUrl" label="介绍文档路径">
        <el-input v-model="form.helperUrl" placeholder="请填入内容" />
      </el-form-item>

      <el-form-item label="高级选项">
        <div>
          <el-checkbox v-model="form.autoOpen">功能默认开通</el-checkbox>
        </div>
        <div>
          <el-checkbox v-model="form.canNotClose">功能开通后不可关闭</el-checkbox>
        </div>
      </el-form-item>
    </el-form>

    <div slot="footer" v-loading="loading" class="dialog-footer">
      <el-button @click="close">放弃</el-button>
      <el-button type="primary" @click="handleSave">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getGroupList } from '@/api/perm'
import { getFeature, updateFeature, addFeature } from '@/api/feature'

import { imgUploadUrl } from '@/api/upload'

export default {
  name: 'FeatureFormDialog',
  props: {
    scope: {
      type: Number,
      require: true
    }
  },
  data() {
    return {
      loading: false,
      visible: false,
      title: '',
      mode: '',
      reject: null,
      resolve: null,
      featureId: null,
      baseUrl: null,
      uploadHeaders: {},
      actionUrl: imgUploadUrl,
      icon: '',
      groupList: [],
      form: {
        icon: null,
        name: null,
        description: null,
        remark: null,
        helperUrl: null,
        permGroups: [],
        webUrl: null,
        autoOpen: false,
        canClose: true,
        canNotClose: false
      },
      rules: {
        name: [{
          required: true,
          message: '请输入功能名称',
          trigger: 'blur'
        }],
        icon: [{
          required: true,
          message: '请上传图标'
        }],
        code: [{
          required: true,
          message: '请输入功能编码',
          trigger: 'blur'
        }],
        description: [{
          required: true,
          message: '请输入描述',
          trigger: 'blur'
        }],
        permGroups: [{
          required: true,
          message: '请选择权限集',
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    ...mapGetters(['resBaseUrl'])
  },
  methods: {
    defaultForm() {
      return {
        icon: null,
        name: null,
        description: null,
        remark: null,
        helperUrl: null,
        permGroups: [],
        webUrl: null,
        autoOpen: false,
        canClose: true,
        canNotClose: false
      }
    },
    fetchGroupList() {
      getGroupList(this.scope).then((res) => {
        if (res.code === 0) {
          this.groupList = res.data
        }
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.icon = res.data.baseUrl + res.data.path
        this.form.icon = res.data.path
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.msg)
      }
    },

    // 上传前处理
    beforeAvatarUpload(file) {
      return this.$beforeUploadImg(file, this, 1000, 1000, 1)
    },

    add() {
      return new Promise((resolve, reject) => {
        this.fetchGroupList()
        this.resolve = resolve
        this.reject = reject
        this.visible = true
        this.mode = 'add'
        this.title = '新增功能'
        this.form = this.defaultForm()
        this.icon = null
      })
    },
    edit(featureId) {
      return new Promise((resolve, reject) => {
        this.fetchGroupList()
        this.resolve = resolve
        this.reject = reject
        this.visible = true
        this.mode = 'edit'
        this.title = '编辑功能'
        this.loading = true
        getFeature(this.scope, featureId).then(res => {
          this.loading = false
          if (res.code === 0) {
            const data = res.data
            const permGroupsTemp = data.permGroups.split(',')
            const permGroups = []
            let i = 0
            for (i = 0; i < permGroupsTemp.length; i++) {
              permGroups.push(Number(permGroupsTemp[i]))
            }
            data.permGroups = permGroups
            data.canNotClose = !data.canClose
            this.icon = this.resBaseUrl + data.icon
            this.form = data
          }
        }).catch(() => {
          this.loading = false
        })
        this.featureId = featureId
      })
    },
    close() {
      this.visible = false
      this.resolve = null
      this.reject = null
      this.$refs.form.resetFields()
    },
    handleSave() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const data = JSON.parse(JSON.stringify(this.form))
          data.permGroups = data.permGroups.join(',')
          data.canClose = !data.canNotClose
          if (this.mode === 'add') {
            addFeature(this.scope, data).then((resp) => {
              this.loading = false
              if (resp.code === 0) {
                this.$notify({ title: '成功', message: '添加成功', type: 'success', duration: 2000 })
                this.resolve && this.resolve()
                this.close()
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            data['id'] = this.featureId
            updateFeature(this.scope, data).then((resp) => {
              this.loading = false
              if (resp.code === 0) {
                this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
                this.resolve && this.resolve()
                this.close()
              }
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-form-item {
    margin-bottom: 15px;
  }

  /* 上传 */
  .app-uploader-img-plus {
    width: 100px;
    height: 100px;
    border: 1px dotted #ddd;
  }

  .app-uploader-img-plus-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .upload-tips {
    margin: 20px 0 0 20px;
    li {
      margin-top: 10px;
      font-size: 14px;
      line-height: 16px;
      color: #999;
    }
  }
  .el-select-dropdown.is-multiple .el-select-dropdown__item.selected{
	  color: $btnBgc;
  }
</style>
